<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC to DASH Live Streaming</title>
    <style>
        video {
            width: 50%;
            height: 30%;
        }
    </style>
</head>
<body>
<h1>WebRTC to DASH Live Streaming Demo</h1>
<button id="startButton">Start Streaming</button>
<div style="float: left;">
    <video id="localVideo" autoplay></video>
</div>
<div style="float: left;">
    <video id="remoteVideo" controls></video>
</div>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script src="https://cdn.dashjs.org/latest/dash.all.min.js"></script>
<script>
    const localVideo = document.getElementById('localVideo');
    const remoteVideo = document.getElementById('remoteVideo');
    const startButton = document.getElementById('startButton');

    let localStream;
    let socket;

    async function startStream() {
        try {
            // 获取摄像头视频流
            localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
            localVideo.srcObject = localStream;
            // 连接到 WebSocket 服务器
            socket = io('ws://192.168.2.20:8081');
            // 发送视频流到服务器
            socket.on('connect', () => {
                console.log('Connected to WebSocket server');
                socket.emit('startStream', { sessionId: socket.id });
                // 设置远程视频播放器
                const url = 'http://124.70.49.99:8080/dash/stream.mpd';
                const player = dashjs.MediaPlayer().create();
                player.initialize(remoteVideo, url, true);
            });

            // 使用 open 事件替代 connect 事件
            socket.on('open', () => {
                console.log('WebSocket connection opened');
            });


            // 监听来自服务器的消息
            socket.on('message', (data) => {
                console.log('Received message from server:', data);
            });

            // 监听连接关闭
            socket.on('disconnect', () => {
                console.log('Disconnected from WebSocket server');
            });
        } catch (err) {
            console.error('Error accessing media devices.', err);
        }
    }

    startButton.addEventListener('click', startStream);
</script>
</body>
</html>